package com.lagou.edu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lagou.edu.common.date.DateUtil;
import com.lagou.edu.common.random.RandomUtil;
import com.lagou.edu.user.entity.PhoneVerificationCode;
import com.lagou.edu.user.exception.ExpireCodeRuntimeException;
import com.lagou.edu.user.exception.IncorrectCodeRuntimteException;
import com.lagou.edu.user.mapper.PhoneVerificationCodeMapper;
import com.lagou.edu.user.service.IPhoneVerificationCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LiuQiang
 * @since 2021-08-25
 */
@Slf4j
@Service
public class PhoneVerificationCodeServiceImpl
        extends ServiceImpl<PhoneVerificationCodeMapper, PhoneVerificationCode>
        implements IPhoneVerificationCodeService {

    @Override
    public boolean save(String telephone) {
        // 获取动态验证码
        String randomNumber = RandomUtil.getRandomNumber(6);
        // 发送验证码 TODO
        log.info("用户登录({})，验证码为:{}", telephone, randomNumber);

        PhoneVerificationCode verificationCode = new PhoneVerificationCode();
        verificationCode.setPhone(telephone);   //设置电话号码
        verificationCode.setVerificationCode(randomNumber);
        verificationCode.setCreateTime(new Date());
        verificationCode.setIsCheck(false);
        verificationCode.setCheckTimes(0);

        //保存验证码
        return this.save(verificationCode);
    }

    @Override
    public boolean checkCode(String telephone, String code) {
        //判断验证码是否存在
        QueryWrapper<PhoneVerificationCode> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", telephone);
        queryWrapper.eq("verification_code", code);
        PhoneVerificationCode verificationCode = this.getBaseMapper().selectOne(queryWrapper);

        if (verificationCode == null) {
            throw new IncorrectCodeRuntimteException("验证码错误");
        }
        //判断验证码是否过期，创建时间添加5分钟，与当前系统时间比较
        Date now = new Date();
        Date expireDate = DateUtil.rollByMinutes(verificationCode.getCreateTime(), 5);
        if (now.getTime() > expireDate.getTime()) {
            throw new ExpireCodeRuntimeException("验证码失效,重新发送");
        }

        // 记录校验次数
        verificationCode.setIsCheck(true);
        int checkTimes = verificationCode.getCheckTimes() + 1;
        verificationCode.setCheckTimes(checkTimes);

        return this.updateById(verificationCode);
    }

}
